package com.blb.shiro3_1;

import java.io.IOException;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.blb.entity.User;
import com.blb.entity.UserExample;
import com.blb.mapper.UserMapper;
import com.blb.utils.MybatisUtils;

public class MyRealm extends AuthorizingRealm {
	

	/**
	 * 登录认证
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("1");
		
		//获取当前用户名
		String username = (String)token.getPrincipal();
		
		try {
			SqlSession session = MybatisUtils.getSession();
			UserMapper userMapper = session.getMapper(UserMapper.class);
			UserExample userExample = new UserExample();
			userExample.createCriteria().andUsernameEqualTo(username);
			List<User> list = userMapper.selectByExample(userExample);
			if(list.isEmpty()){
				return null;
			}
			
			User user = list.get(0);
			if(user.getState()==-1){
				throw new LockedAccountException();
			}
			
			//用户信息，密码，getName();
			return new SimpleAuthenticationInfo(username,user.getPassword(),getName());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	/**
	 * 授权
	 *根据用户名获得角色信息和权限
	 * @param arg0
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		String username = (String) principal.getPrimaryPrincipal();
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		
		try {
			SqlSession session = MybatisUtils.getSession();
			UserMapper userMapper = session.getMapper(UserMapper.class);
			
			//根据用户名获取角色名
			List<String> roles = userMapper.getRoles(username);
			System.out.println(roles);
			simpleAuthorizationInfo.addRoles(roles);	
			
			//权限
			List<String> permission = userMapper.getStringPermission(roles);
			System.out.println(permission);
			simpleAuthorizationInfo.addStringPermissions(permission);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	
		
		return simpleAuthorizationInfo;
	}



}
